import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'follow_list_page_controller.dart';
import '../../function/utils/my_common.dart';
import '../../function/model/user_model.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

/// 关注和粉丝列表页面组件
/// 使用非常规命名避免标准模式
class FollowListPage extends GetView<FollowListPageController> {
  const FollowListPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/communal_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopBar(),

              // 用户列表
              Expanded(child: _buildUserList()),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          Icon(
            Icons.arrow_back_ios,
            color: MyCommonUtils.white,
            size: 24.sp,
          ).inkWell(onTap: controller.goBack),

          SizedBox(width: 16.w),

          // 页面标题
          Expanded(
            child: Text(
              controller.pageTitle,
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 24.sp,
                fontWeight: FontWeight.bold,
                color: MyCommonUtils.white,
                fontFamily:
                    GoogleFonts.berkshireSwash(
                      fontWeight: FontWeight.w400,
                    ).fontFamily,
                letterSpacing: 1.2,
              ),
            ),
          ),

          SizedBox(width: 40.w), // 占位符，保持标题居中
        ],
      ),
    );
  }

  // 删除未使用的占位方法

  /// 构建用户列表
  Widget _buildUserList() {
    return Obx(() {
      final users = controller.currentUserList;

      if (users.isEmpty) {
        return _buildEmptyState();
      }

      return MasonryGridView.count(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        crossAxisCount: 1,
        mainAxisSpacing: 12.h,
        itemCount: users.length,
        itemBuilder: (context, index) {
          final user = users[index];
          return _StaggeredSlideIn(index: index, child: _buildUserItem(user));
        },
      );
    });
  }

  /// 构建空状态（根据页面类型展示不同文案）
  Widget _buildEmptyState() {
    final isFollowing = controller.pageTitle == 'Following';
    final message = isFollowing ? 'No following yet' : 'No followers yet';
    final subtitle =
        isFollowing
            ? 'Start following people to see them here'
            : 'When people follow you, they\'ll appear here';

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            isFollowing ? Icons.person_add : Icons.people,
            size: 80.sp,
            color: MyCommonUtils.white.withOpacity(0.5),
          ),
          SizedBox(height: 24.h),
          Text(
            message,
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.bold,
              color: MyCommonUtils.white,
            ),
          ),
          SizedBox(height: 12.h),
          Text(
            subtitle,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 16.sp,
              color: MyCommonUtils.white.withOpacity(0.7),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建用户项
  Widget _buildUserItem(UserModel user) {
    final isCurrentUser = user.id == controller.currentUser?.id;
    final isFollowing = controller.isFollowing(user.id);

    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      padding: EdgeInsets.only(left: 6.w, bottom: 7.h),
      decoration: BoxDecoration(
        color: MyCommonUtils.black,
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Container(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Color(0xFF004D36),
          borderRadius: BorderRadius.circular(16.r),
          border: Border.all(color: MyCommonUtils.blue, width: 2.w),
        ),
        child: Row(
          children: [
            // 用户头像
            GestureDetector(
              onTap: () => controller.goToUserProfile(user),
              child: CircleAvatar(
                radius: 25.w,
                backgroundImage: AssetImage(user.avatar),
              ),
            ),

            SizedBox(width: 16.w),

            // 用户信息
            Expanded(
              child: GestureDetector(
                onTap: () => controller.goToUserProfile(user),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户名
                    Text(
                      user.nickname.isNotEmpty ? user.nickname : user.username,
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.bold,
                        color: MyCommonUtils.white,
                      ),
                    ),

                    SizedBox(height: 4.h),

                    // 用户签名
                    Text(
                      user.signature.isNotEmpty
                          ? user.signature
                          : 'Plant lover and nature enthusiast',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: MyCommonUtils.white.withOpacity(0.8),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
            ),

            // 关注按钮（只有不是自己的时候才显示）
            if (!isCurrentUser) _buildFollowButton(user, isFollowing),
          ],
        ),
      ),
    );
  }

  /// 构建关注按钮
  Widget _buildFollowButton(UserModel user, bool isFollowing) {
    return Obx(() {
      final currentFollowingState = controller.isFollowing(user.id);
      return (currentFollowingState
              ? Image.asset(
                'assets/images/followed.png',
                width: 20.w,
                height: 20.w,
              )
              : Image.asset(
                'assets/images/follow.png',
                width: 20.w,
                height: 20.w,
              ))
          .padding(horizontal: 12.w, vertical: 6.h)
          .card(
            color:
                currentFollowingState
                    ? MyCommonUtils.white
                    : MyCommonUtils.blue,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(20.r),
            ),
          )
          .inkWell(
            onTap: () => controller.toggleFollow(user),
            borderRadius: 20.r,
          );
    });
  }
}

/// 进场动画：左右交替滑入 + 渐隐
class _StaggeredSlideIn extends StatefulWidget {
  final int index;
  final Widget child;
  const _StaggeredSlideIn({required this.index, required this.child});

  @override
  State<_StaggeredSlideIn> createState() => _StaggeredSlideInState();
}

class _StaggeredSlideInState extends State<_StaggeredSlideIn>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;
  late final Animation<double> _opacity;
  late final Animation<Offset> _offset;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 420),
    );

    final bool fromLeft = widget.index % 2 == 0;
    _offset = Tween<Offset>(
      begin: Offset(fromLeft ? -0.2 : 0.2, 0),
      end: Offset.zero,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOutCubic));

    _opacity = Tween<double>(
      begin: 0,
      end: 1,
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut));

    // 分段延迟，形成staggered效果
    Future.delayed(Duration(milliseconds: 60 * widget.index), () {
      if (mounted) _controller.forward();
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return FadeTransition(
      opacity: _opacity,
      child: SlideTransition(position: _offset, child: widget.child),
    );
  }
}
